package com.olddriver.crm.service.impl;

import com.olddriver.crm.domain.Role;
import com.olddriver.crm.mapper.RoleMapper;
import com.olddriver.crm.page.PageResult;
import com.olddriver.crm.query.QueryObject;
import com.olddriver.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void insert(Role role) {
        roleMapper.insert(role);
        roleMapper.insertRelations(role.getId(), role.getPermissions());
    }

    @Override
    public void update(Role role) {
        roleMapper.deleteRelations(role.getId());
        roleMapper.update(role);
        roleMapper.insertRelations(role.getId(), role.getPermissions());
    }

    @Override
    public PageResult query(QueryObject qo) {
        int total = roleMapper.queryTotal(qo);
        if (total == 0) {
            return new PageResult(total, Collections.emptyList());
        }
        return new PageResult(total, roleMapper.queryRows(qo));
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteRelations(id);
        roleMapper.deleteById(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.find();
    }
}
